<template>
  <div class="user-profile">
    <div class="page-header">
      <h1>个人信息</h1>
      <div class="breadcrumb">系统管理 / 个人信息</div>
    </div>

    <div class="profile-content">
      <!-- 个人信息卡片 -->
      <div class="profile-card">
        <div class="profile-header">
          <div class="avatar-section">
            <div class="avatar" :style="{ backgroundImage: `url(${userInfo.avatarUrl || '/default-avatar.png'})` }">
              <div class="avatar-upload" @click="showAvatarUpload = true">
                <span class="upload-icon">📷</span>
              </div>
            </div>
            <div class="avatar-info">
              <h3>{{ userInfo.name || '未设置姓名' }}</h3>
              <p class="username">@{{ userInfo.username }}</p>
              <p class="role" v-if="userInfo.isSuperAdmin">超级管理员</p>
            </div>
          </div>
          <div class="profile-actions">
            <button class="btn btn-primary" @click="editMode = true" v-if="!editMode">
              <span class="btn-icon">✏️</span>
              编辑信息
            </button>
            <div class="edit-actions" v-if="editMode">
              <button class="btn btn-success" @click="saveProfile">
                <span class="btn-icon">💾</span>
                保存
              </button>
              <button class="btn btn-secondary" @click="cancelEdit">
                <span class="btn-icon">❌</span>
                取消
              </button>
            </div>
          </div>
        </div>

        <!-- 个人信息表单 -->
        <div class="profile-form">
          <div class="form-row">
            <div class="form-group">
              <label>姓名</label>
              <input 
                v-model="editForm.name" 
                type="text" 
                placeholder="请输入姓名"
                :disabled="!editMode"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>用户名</label>
              <input 
                v-model="userInfo.username" 
                type="text" 
                disabled
                class="form-input disabled"
              />
              <small class="form-hint">用户名不可修改</small>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>邮箱</label>
              <input 
                v-model="editForm.email" 
                type="email" 
                placeholder="请输入邮箱"
                :disabled="!editMode"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>手机号</label>
              <input 
                v-model="editForm.mobile" 
                type="tel" 
                placeholder="请输入手机号"
                :disabled="!editMode"
                class="form-input"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>部门</label>
              <input 
                v-model="editForm.department" 
                type="text" 
                placeholder="请输入部门"
                :disabled="!editMode"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>职位</label>
              <input 
                v-model="editForm.position" 
                type="text" 
                placeholder="请输入职位"
                :disabled="!editMode"
                class="form-input"
              />
            </div>
          </div>

          <div class="form-group full-width">
            <label>个人简介</label>
            <textarea 
              v-model="editForm.bio" 
              placeholder="请输入个人简介"
              :disabled="!editMode"
              class="form-textarea"
              rows="4"
            ></textarea>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>状态</label>
              <div class="status-badge" :class="getStatusClass(userInfo.status)">
                {{ getStatusText(userInfo.status) }}
              </div>
            </div>
            <div class="form-group">
              <label>最后登录</label>
              <div class="last-login">
                {{ formatDateTime(userInfo.lastLoginAt) }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 账户信息卡片 -->
      <div class="account-card">
        <h3>账户信息</h3>
        <div class="account-info">
          <div class="info-item">
            <span class="label">用户ID：</span>
            <span class="value">{{ userInfo.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDateTime(userInfo.createdAt) }}</span>
          </div>
          <div class="info-item">
            <span class="label">更新时间：</span>
            <span class="value">{{ formatDateTime(userInfo.updatedAt) }}</span>
          </div>
        </div>
        <div class="account-actions">
          <button class="btn btn-warning" @click="goToChangePassword">
            <span class="btn-icon">🔒</span>
            修改密码
          </button>
        </div>
      </div>
    </div>

    <!-- 头像上传模态框 -->
    <div v-if="showAvatarUpload" class="modal-overlay" @click="showAvatarUpload = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>上传头像</h3>
          <button class="modal-close" @click="showAvatarUpload = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="avatar-upload-form">
            <div class="upload-area">
              <input 
                id="avatarFile"
                type="file" 
                accept="image/*" 
                @change="handleAvatarChange"
                style="display: none"
              />
              <div class="upload-placeholder" @click="selectFile">
                <span class="upload-icon">📁</span>
                <p>点击选择图片</p>
                <small>支持 JPG、PNG 格式，最大 5MB</small>
              </div>
            </div>
            <div v-if="selectedAvatar" class="avatar-preview">
              <img :src="selectedAvatar" alt="头像预览" />
              <button class="btn btn-primary" @click="uploadAvatar">确认上传</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码模态框 -->
    <div v-if="showChangePassword" class="modal-overlay" @click="showChangePassword = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>修改密码</h3>
          <button class="modal-close" @click="showChangePassword = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="password-form">
            <div class="form-group">
              <label>当前密码</label>
              <input 
                v-model="passwordForm.oldPassword" 
                type="password" 
                placeholder="请输入当前密码"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>新密码</label>
              <input 
                v-model="passwordForm.newPassword" 
                type="password" 
                placeholder="请输入新密码"
                class="form-input"
              />
              <small class="form-hint">密码长度至少6位</small>
            </div>
            <div class="form-group">
              <label>确认新密码</label>
              <input 
                v-model="passwordForm.confirmPassword" 
                type="password" 
                placeholder="请再次输入新密码"
                class="form-input"
              />
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showChangePassword = false">取消</button>
          <button class="btn btn-primary" @click="changePassword" :disabled="!canChangePassword">
            确认修改
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { apiGet, apiPut, getCurrentUser } from '../../utils/api.js'

const router = useRouter()

// 响应式数据
const userInfo = ref({})
const editMode = ref(false)
const showAvatarUpload = ref(false)
const showChangePassword = ref(false)
const selectedAvatar = ref(null)

// 编辑表单
const editForm = reactive({
  name: '',
  email: '',
  mobile: '',
  department: '',
  position: '',
  bio: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 计算属性
const canChangePassword = computed(() => {
  return passwordForm.oldPassword && 
         passwordForm.newPassword && 
         passwordForm.confirmPassword &&
         passwordForm.newPassword === passwordForm.confirmPassword &&
         passwordForm.newPassword.length >= 6
})

// 生命周期
onMounted(() => {
  loadUserProfile()
})

// 方法
const loadUserProfile = async () => {
  try {
    const current = getCurrentUser()
    const userId = current?.id
    let response
    if (userId) {
      response = await apiGet(`/system/user/profile/${userId}`)
    } else if (current?.username) {
      response = await apiGet(`/system/user/profile/by-username?username=${encodeURIComponent(current.username)}`)
    } else {
      throw new Error('未获取到当前登录用户ID')
    }
    
    if (response) {
      userInfo.value = response
      // 初始化编辑表单
      Object.assign(editForm, {
        name: response.name || '',
        email: response.email || '',
        mobile: response.mobile || '',
        department: response.department || '',
        position: response.position || '',
        bio: response.bio || ''
      })
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    alert('加载用户信息失败')
  }
}

const saveProfile = async () => {
  try {
    const userId = userInfo.value.id
    const response = await apiPut(`/system/user/profile/${userId}`, editForm)
    
    if (response && response.message) {
      alert('个人信息更新成功')
      editMode.value = false
      await loadUserProfile() // 重新加载数据
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
    alert('更新个人信息失败: ' + (error.message || '未知错误'))
  }
}

const cancelEdit = () => {
  editMode.value = false
  // 恢复原始数据
  Object.assign(editForm, {
    name: userInfo.value.name || '',
    email: userInfo.value.email || '',
    mobile: userInfo.value.mobile || '',
    department: userInfo.value.department || '',
    position: userInfo.value.position || '',
    bio: userInfo.value.bio || ''
  })
}

const selectFile = () => {
  const fileInput = document.getElementById('avatarFile')
  if (fileInput) {
    fileInput.click()
  }
}

const handleAvatarChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    if (file.size > 5 * 1024 * 1024) {
      alert('图片大小不能超过5MB')
      return
    }
    
    const reader = new FileReader()
    reader.onload = (e) => {
      selectedAvatar.value = e.target.result
    }
    reader.readAsDataURL(file)
  }
}

const uploadAvatar = async () => {
  try {
    const userId = userInfo.value.id
    const fileInput = document.getElementById('avatarFile')
    const file = fileInput.files[0]
    
    if (!file) {
      alert('请选择要上传的文件')
      return
    }
    
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', file)
    
    // 发送文件上传请求
    const response = await fetch(`/api/system/user/upload-avatar/${userId}`, {
      method: 'POST',
      body: formData,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`上传失败: ${response.status}`)
    }
    
    const result = await response.json()
    
    if (result.message) {
      alert('头像上传成功')
      userInfo.value.avatarUrl = result.fileUrl
      showAvatarUpload.value = false
      selectedAvatar.value = null
      // 清空文件输入
      fileInput.value = ''
      
      // 通知父组件更新头像
      window.dispatchEvent(new CustomEvent('avatarUpdated', { 
        detail: { avatarUrl: result.fileUrl } 
      }))
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    alert('上传头像失败: ' + (error.message || '未知错误'))
  }
}

const goToChangePassword = () => {
  router.push('/system/change-password')
}

const changePassword = async () => {
  try {
    const userId = userInfo.value.id
    const response = await apiPut(`/system/user/password/${userId}`, {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (response && response.message) {
      alert('密码修改成功')
      showChangePassword.value = false
      // 清空表单
      Object.assign(passwordForm, {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    alert('修改密码失败: ' + (error.message || '未知错误'))
  }
}

const getStatusClass = (status) => {
  switch (status) {
    case 1: return 'status-active'
    case 0: return 'status-inactive'
    case 2: return 'status-locked'
    default: return 'status-unknown'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 1: return '启用'
    case 0: return '停用'
    case 2: return '锁定'
    default: return '未知'
  }
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '未设置'
  return new Date(dateTime).toLocaleString('zh-CN')
}
</script>

<style scoped>
.user-profile {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
}

.breadcrumb {
  color: #7f8c8d;
  font-size: 14px;
}

.profile-content {
  display: grid;
  gap: 24px;
  grid-template-columns: 2fr 1fr;
}

.profile-card, .account-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-size: cover;
  background-position: center;
  background-color: #e5e7eb;
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.avatar-upload {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background: #667eea;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.avatar-upload:hover {
  background: #5a67d8;
  transform: scale(1.1);
}

.upload-icon {
  color: white;
  font-size: 16px;
}

.avatar-info h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.username {
  margin: 0 0 4px 0;
  color: #7f8c8d;
  font-size: 16px;
}

.role {
  margin: 0;
  color: #667eea;
  font-size: 14px;
  font-weight: 500;
  background: rgba(102, 126, 234, 0.1);
  padding: 4px 12px;
  border-radius: 20px;
  display: inline-block;
}

.profile-actions {
  display: flex;
  gap: 12px;
}

.edit-actions {
  display: flex;
  gap: 12px;
}

.profile-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  margin-bottom: 8px;
  color: #374151;
  font-weight: 500;
  font-size: 14px;
}

.form-input, .form-textarea {
  padding: 12px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-input.disabled {
  background: #f9fafb;
  color: #6b7280;
  cursor: not-allowed;
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.form-hint {
  margin-top: 4px;
  color: #6b7280;
  font-size: 12px;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  display: inline-block;
}

.status-active {
  background: #d1fae5;
  color: #065f46;
}

.status-inactive {
  background: #fee2e2;
  color: #991b1b;
}

.status-locked {
  background: #fef3c7;
  color: #92400e;
}

.status-unknown {
  background: #f3f4f6;
  color: #374151;
}

.last-login {
  color: #6b7280;
  font-size: 14px;
}

.account-card h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
}

.account-info {
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item .label {
  color: #6b7280;
  font-size: 14px;
}

.info-item .value {
  color: #374151;
  font-size: 14px;
  font-weight: 500;
}

.account-actions {
  display: flex;
  justify-content: center;
}

/* 按钮样式 */
.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover {
  background: #5a67d8;
}

.btn-success {
  background: #10b981;
  color: white;
}

.btn-success:hover {
  background: #059669;
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover {
  background: #4b5563;
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-warning:hover {
  background: #d97706;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-icon {
  font-size: 16px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.modal-close {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s ease;
}

.modal-close:hover {
  background: rgba(255, 255, 255, 0.2);
}

.modal-body {
  padding: 24px;
}

.modal-footer {
  padding: 20px 24px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background: #f9fafb;
  border-radius: 0 0 12px 12px;
}

/* 头像上传样式 */
.avatar-upload-form {
  text-align: center;
}

.upload-area {
  margin-bottom: 20px;
}

.upload-placeholder {
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  padding: 40px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-placeholder:hover {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

.upload-placeholder .upload-icon {
  font-size: 48px;
  color: #9ca3af;
  margin-bottom: 16px;
  display: block;
}

.upload-placeholder p {
  margin: 0 0 8px 0;
  color: #374151;
  font-weight: 500;
}

.upload-placeholder small {
  color: #6b7280;
  font-size: 12px;
}

.avatar-preview {
  margin-top: 20px;
}

.avatar-preview img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 16px;
}

/* 密码表单样式 */
.password-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-content {
    grid-template-columns: 1fr;
  }
  
  .profile-header {
    flex-direction: column;
    gap: 20px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
}
</style>
